package com.guddqs.monkey.shop.utils;

import com.guddqs.util.HttpUtils;
import com.guddqs.util.JsonUtils;
import com.guddqs.util.StringUtil;
import org.jboss.logging.Logger;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author wq
 * @date 2018/11/13
 * @description 云片网 短信接口
 */
public class SmsUtil {

    private static String apiKey;
    private static Logger logger;
    private static String dev;

    private static void getResource() {
        if (apiKey == null) {
            apiKey = SpringContextUtil.getProperty("sms.apiKey");
            logger = Logger.getLogger(SmsUtil.class);
            dev = SpringContextUtil.getEnvironmentProperty("mail.dev");
        }
    }

    public static String sendSms(String mobile, String tplId, Map<String, String> data) throws IOException {
        getResource();
        if ("1".equals(dev)) {
            return null;
        }
        logger.info(StringUtil.format("sendSms--> mobile: %s; tplId: %s; data: %s", mobile, tplId, JsonUtils.getJsonString(data)));
        Map<String, String> params = new HashMap<>(5);
        params.put("apikey", apiKey);
        params.put("mobile", mobile);
        params.put("tpl_id", tplId);
        StringBuilder dataSbf = new StringBuilder();
        for (String dataKey : data.keySet()) {
            String value = data.get(dataKey);
            value = value.replaceAll("【", "(");
            value = value.replaceAll("】", ")");
            dataSbf.append(URLEncoder.encode("#" + dataKey + "#", "UTF-8")).append("=").append(URLEncoder.encode(value, "UTF-8")).append("&");
        }
        logger.info("sendSms--> dataSbf: " + dataSbf.toString());
        params.put("tpl_value", dataSbf.toString());
        String res = HttpUtils.httpClientPost("https://sms.yunpian.com/v2/sms/tpl_batch_send.json", null, params);
        logger.info("sendSms--> res: " + res);
        return res;
    }

}
